﻿using System;
using System.Diagnostics;
using System.Runtime.Caching;
using Tools.Api.Cache;

namespace Tools.Cache {

    /// <summary>
    /// 内存缓存
    /// Adatper模式
    /// </summary>
    public class MemoryCacheAdatper : ICacheStorage {

        readonly MemoryCache _memoryCache = MemoryCache.Default;

        public void Remove(string key) {
            _memoryCache.Remove(key);
        }

        public void Store(string key, object data) {
            _memoryCache.Set(key, data, DateTimeOffset.Now.AddMinutes(30));
        }

        public T Retrieve<T>(string key) {
            try {
                T itemStored = (T)_memoryCache.Get(key);
                if (itemStored == null) {
                    itemStored = default(T);
                }
                return itemStored;
            }
            catch (Exception ex) {
                Debug.WriteLine(ex.StackTrace);
                return default(T);
            }
        }

        public T Pull<T>(string key, Func<T> method) {
            T val = Retrieve<T>(key);
            if (val == null) {
                val = method();
                Store(key, val);
            }
            return val;
        }
    }
}
